﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.IO.IsolatedStorage;
using Newtonsoft.Json;

namespace ElectricityMate
{
    public class ItemViewModel
    {
        public string DateAndConsumption { get; set; }
        public string AverageHourlyConsumption { get; set; }
    }
    public class ViewModel
    {
        public ViewModel()
        {
            Items = new ObservableCollection<ItemViewModel>();
        }

        /// <summary>
        /// A collection for ItemViewModel objects.
        /// </summary>
        public ObservableCollection<ItemViewModel> Items { get; private set; }

        private string _sampleProperty = "Sample Runtime Property Value";
        /// <summary>
        /// Sample ViewModel property; this property is used in the view to display its value using a Binding
        /// </summary>
        /// <returns></returns>
        public string SampleProperty
        {
            get
            {
                return _sampleProperty;
            }
            set
            {
                if (value != _sampleProperty)
                {
                    _sampleProperty = value;
                    NotifyPropertyChanged("SampleProperty");
                }
            }
        }

        public int FlashesPerKWh
        {
            get
            {
                return IsolatedStorageSettings.ApplicationSettings.Contains("FlashesPerKWH")
                           ? (int)IsolatedStorageSettings.ApplicationSettings["FlashesPerKWH"]
                           : 10000;
            }
            set
            {
                if (!IsolatedStorageSettings.ApplicationSettings.Contains("FlashesPerKWH"))
                    IsolatedStorageSettings.ApplicationSettings.Add("FlashesPerKWH", value);
                else 
                    IsolatedStorageSettings.ApplicationSettings["FlashesPerKWH"] = value;

                IsolatedStorageSettings.ApplicationSettings.Save();

            }
        }

        public bool IsDataLoaded
        {
            get;
            private set;
        }

        /// <summary>
        /// Creates and adds a few ItemViewModel objects into the Items collection.
        /// </summary>
        public void LoadData()
        {
            using (var store = IsolatedStorageFile.GetUserStoreForApplication())
            {
                if (!store.FileExists("measurements.json"))
                {
                    var stream = store.CreateFile("measurements.json");
                    stream.Close();
                }
                using (var stream = store.OpenFile("measurements.json", FileMode.Open, FileAccess.Read))
                using (var reader = new StreamReader(stream))
                {
                    IsDataLoaded = true;
                    try
                    {
                        // Read a line from the file and add it to sb.
                        var sb = reader.ReadLine();
                        if (sb == null)
                        {
                            return;
                        }

                        // measurements is saved in json format
                        var json = sb;
                        var items = JsonConvert.DeserializeObject<List<ItemViewModel>>(json);
                        items.ForEach(Items.Add);
                        reader.Close();
                        stream.Close();
                    }
                    catch (Exception ex)
                    {
                        System.Diagnostics.Debug.WriteLine("failed to load file: " + ex.Message);
                    }

                }
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;
        private void NotifyPropertyChanged(String propertyName)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (null != handler)
            {
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
        }

    }
}